package api

import (
	"github.com/gin-gonic/gin"
	"go_api/config"
	"go_api/model"
	"go_api/pkg/validator"
	"go_api/request"
)

type GroupController struct {
	BaseController
}

// GetGroupList 获取所有分组数据
func (group GroupController) GetGroupList(c *gin.Context) {

	groupModel := model.XGroup{}
	items := groupModel.GetGroupList()

	group.responseSuccess(c, items)
}

// CreateGroup 新增分组信息
func (group GroupController) CreateGroup(c *gin.Context) {
	uId := c.GetInt("uId")
	if uId == 0 {
		group.responseError(c, 401, "缺少登陆信息")
		return
	}
	//数据验证
	var data request.CreateGroupRequest
	msg, ok := validator.ValidatorData(c, &data)
	if !ok {
		group.responseError(c, 1, msg)
		return
	}

	tx := config.Mdb.Begin()

	groupModel := model.XGroup{}
	groupModel.GroupName = data.GroupName
	groupModel.GroupDesc = data.GroupDesc
	groupModel.IsDel = 2

	err := groupModel.CreateTxGroup(tx)
	if err != nil {
		// 发生错误回滚事务
		tx.Rollback()
		group.responseError(c, 1, "分组创建失败")
		return
	}
	groupUserModel := model.XGroupUser{
		GroupID: groupModel.ID,
		UserID:  uId,
		Role:    1,
		IsDel:   2,
	}

	err = groupUserModel.CreateTxGroupUser(tx)
	if err != nil {
		// 发生错误回滚事务
		tx.Rollback()
		group.responseError(c, 1, "分组用户创建失败")
		return
	}
	// 提交这个事务
	tx.Commit()
	group.responseSuccess(c, nil)
}

// EditGroup 编辑分组信息
func (group GroupController) EditGroup(c *gin.Context) {
	uId := c.GetInt("uId")
	if uId == 0 {
		group.responseError(c, 401, "缺少登陆信息")
		return
	}
	//数据验证
	var data request.EditGroupRequest
	msg, ok := validator.ValidatorData(c, &data)
	if !ok {
		group.responseError(c, 1, msg)
		return
	}

	groupModel := model.XGroup{}
	groupModel.GroupName = data.GroupName
	groupModel.GroupDesc = data.GroupDesc

	err := groupModel.EditGroup(data.GroupId)
	if err != nil {
		group.responseError(c, 1, "更新失败")
		return
	}
	group.responseSuccess(c, nil)
}

// DelGroup 删除分组信息
func (group GroupController) DelGroup(c *gin.Context) {
	uId := c.GetInt("uId")
	if uId == 0 {
		group.responseError(c, 401, "缺少登陆信息")
		return
	}
	//数据验证
	var data request.DelGroupRequest
	msg, ok := validator.ValidatorData(c, &data)
	if !ok {
		group.responseError(c, 1, msg)
		return
	}
	//开启事务
	tx := config.Mdb.Begin()
	//删除分组
	groupModel := model.XGroup{
		ID: data.GroupId,
	}
	err := groupModel.DelGroup(tx)
	if err != nil {
		// 发生错误回滚事务
		tx.Rollback()
		group.responseError(c, 1, "删除失败")
		return
	}
	groupUserModel := model.XGroupUser{}
	err = groupUserModel.DelTxGroupUser(tx, data.GroupId)
	if err != nil {
		// 发生错误回滚事务
		tx.Rollback()
		group.responseError(c, 1, "删除失败")
		return
	}
	//删除项目
	projectModel := model.XProject{}
	err = projectModel.DelTxGroup(tx, data.GroupId)
	if err != nil {
		// 发生错误回滚事务
		tx.Rollback()
		group.responseError(c, 1, "删除失败")
		return
	}
	// 提交这个事务
	tx.Commit()
	group.responseSuccess(c, nil)
}
